//
//  RSWMessageOperation.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/12.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "RSWMessageOperation.h"
#import "RSWMessageOperation+PushMessageDictionaryKeyDefine.h"

@interface CacheChannel : NSObject
{
    NSMutableArray *_cache;
    BOOL _running;
    NSUInteger _tag;
}

@property(nonatomic,retain) NSMutableArray *cache;
@property(nonatomic,assign) BOOL running;
@property(nonatomic,assign) NSUInteger tag;

@end

@implementation CacheChannel

-(id)initWithTag:(NSUInteger)tag;
{
    self = [super init];
    
    _cache = [NSMutableArray new];
    
    _running = NO;
    
    _tag = tag;
    
    return self;
}

@end

@interface PushNotification : NSObject

@property(nonatomic,strong) NSDate *recvDate;
@property(nonatomic,strong) NSDictionary *pushDictionary;
@property(nonatomic,strong) NSString *pushContent;

+(PushNotification*)pushNotificationWithPushContent:(NSString*)content;

@end

@implementation PushNotification

+(PushNotification*)pushNotificationWithPushContent:(NSString *)content
{
    PushNotification *pn = [PushNotification new];
    pn.pushContent = content;
    pn.recvDate = [NSDate date];
    return pn;
}

@end

@implementation RSWMessageOperation
{
    XMSDataOperationManager *_savePuspNotiQueue;
    
    XMSDispatchQueueWrapper *_cacheLockQueue;
    
    CacheChannel *_cacheChannel1;
    CacheChannel *_cacheChannel3;
    
    XMSDataOperationManager *_operationQueue2;
    
    XMSDataOperationManager *_writebackQueue;
}

static RSWMessageOperation *s_mo;

-(id)init
{
    self = [super init];
    
    _savePuspNotiQueue = [XMSDataOperationManager new];
    
    _cacheLockQueue = [[XMSDispatchQueueWrapper alloc]initWithName:"CacheLockQueue"];
    
    _cacheChannel1 = [[CacheChannel alloc]initWithTag:1];
    _cacheChannel3 = [[CacheChannel alloc]initWithTag:3];
    
    _writebackQueue = [[XMSDataOperationManager alloc] initWithDataOperationManagerDelegate:nil AttachDOM:self];
    
    return self;
}


NSString * s_tokenID;

+(void)setTokenID:(NSString*)tokenID
{
    s_tokenID = tokenID;
}

+(NSString*)tokenID
{
    return s_tokenID;
}

+(BOOL)registerNotification
{
#ifdef __IPHONE_8_0
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    else
    {
        UIRemoteNotificationType settings = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:settings];
    }
    
    if([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        return [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
    }
    else
    {
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        
        return type == UIRemoteNotificationTypeNone ? NO : YES;
    }
#else
    UIRemoteNotificationType settings = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:settings];
    UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    return type == UIRemoteNotificationTypeNone ? NO : YES;
#endif
    return NO;
}

+(void)initRSWMessageOperation
{
    if(s_mo == nil)
        s_mo = [RSWMessageOperation new];
}

+(void)releaseRSWMessageOperation
{
    [s_mo suspendOperatePushNotification];
    s_mo = nil;
}

+(void)suspendOperatePushNotification
{
    [s_mo suspendOperatePushNotification];
}

+(void)resumeOperatePushNotification
{
    [s_mo resumeOperatePushNotification];
}

+(void)savePushNotification:(NSDictionary *)pushNoti
{
    [s_mo savePushNotification:pushNoti];
}


-(void)suspendOperatePushNotification
{
    [_writebackQueue terminateRequest];
    [_operationQueue2 terminateRequest];
    [self terminateRequest];
    
    [_cacheLockQueue dispatchThreadSync:^
     {
         _cacheChannel1.running = NO;
         _cacheChannel3.running = NO;
         [_cacheChannel1.cache removeAllObjects];
         [_cacheChannel3.cache removeAllObjects];
     }];
}

-(void)resumeOperatePushNotification
{
    [self cancelTerminateRequest];
    [_operationQueue2 cancelTerminateRequest];
    [_writebackQueue cancelTerminateRequest];
}

-(void)savePushNotification:(NSDictionary *)pushNoti
{
    if([XLGContext context].m_bLogined != YES)
        return;
    
    long recvE = [pushNoti[@"e"] longValue];
    if(recvE == [XLGContext context].m_nUsernumber != YES)
        return;
    
    PushNotification *pn = [PushNotification pushNotificationWithPushContent:pushNoti[@"key1"]];
    
    [_savePuspNotiQueue requestQueuePoolAsyncBlock:^
     {
         if([XLGContext context].m_bLogined != YES)
             return;
         
         [_cacheLockQueue dispatchThreadAsync:^
          {
              if(_cacheChannel1.running == YES)
              {
                  [_cacheChannel3.cache addObject:pn];
              }
              else
              {
                  [_cacheChannel1.cache addObject:pn];
                  [self getMessage:_cacheChannel1 tmpCacheChannel:_cacheChannel3];
              }
          }];
     }];
}

-(XMSDataOperationManager *)operationQueue2
{
    if(_operationQueue2 == nil)
        _operationQueue2 = [[XMSDataOperationManager alloc] initWithDataOperationManagerDelegate:nil AttachDOM:self];
    return _operationQueue2;
}

-(void)getMessage:(CacheChannel*)cacheChannel tmpCacheChannel:(CacheChannel*)tmpCacheChannel
{
    
}

-(void)getMessageWithPushMessageIDType:(PushMessageIDType)pushMessageIDType pushmsgDictionarys:(NSArray *)pushNotifications cacheChannel:(CacheChannel*)cacheChannel tmpCacheChannel:(CacheChannel*)tmpCacheChannel
{
    [self requestThreadBlock:^
     {
         
        
     }];
}

+(void)getChatOfflineMessage:(BOOL)newThread complete:(void(^)(NSInteger nResult))complete
{
    [s_mo getChatOfflineMessage:newThread complete:complete];
}

-(void)getChatOfflineMessage:(BOOL)blockThread complete:(void(^)(NSInteger nResult))complete
{
    if(blockThread == YES)
    {
        [self requestThreadBlock:^
         {
             //[self getChatOfflineMessageComplete:complete];
         }];
    }
    else
    {
        //[self getChatOfflineMessageComplete:complete];
    }
}


+(void)bindPushAsyncCompletion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
#if TARGET_IPHONE_SIMULATOR
    completion(YES,YES,nil);
#else
    RSWMessageOperation *manager = [RSWMessageOperation new];
    [manager bindPush:[s_tokenID copy] deviceKey:[XMSKeychainItemWrapper uniqueKey] asyncCompletion:completion];
#endif
}

-(void)bindPush:(NSString*)tokenID deviceKey:(NSString*)deviceKey asyncCompletion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    [self requestThreadBlock:^
     {
#ifdef DEBUG
         NSInteger deployStatus = 1; //开发
#else
         NSInteger deployStatus = 2; //生产（发布）
#endif
         
         NSLog(@"%ul",deployStatus);
     }];
}
@end
